package com.example.hello.service;

import com.example.hello.dto.LoginDTO;
import com.example.hello.dto.LoginResponseDTO;
import com.example.hello.entity.Employee;
import com.example.hello.mapper.EmployeeMapper;
import com.example.hello.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class LoginService {

    @Autowired
    private EmployeeMapper employeeMapper;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 登录验证
     * @param loginDTO 登录信息
     * @return 登录结果
     */
    public LoginResponseDTO login(LoginDTO loginDTO) {
        log.info("尝试登录: {}", loginDTO.getUsername());
        
        // 根据用户名查询员工
        Employee employee = employeeMapper.selectByUsername(loginDTO.getUsername());
        
        // 验证员工是否存在以及密码是否正确
        if (employee == null) {
            log.warn("用户不存在: {}", loginDTO.getUsername());
            return null;
        }
        
        // 检查密码是否为空
        if (employee.getPassword() == null) {
            log.warn("用户密码为空: {}", loginDTO.getUsername());
            // 临时解决方案：如果密码为空，直接视为登录成功
            // 在实际生产环境中应当修复数据库中的密码数据
            String token = jwtUtil.generateToken(employee.getId(), employee.getUsername());
            return new LoginResponseDTO(
                    employee.getId(),
                    employee.getUsername(),
                    employee.getName(),
                    token
            );
        }
        
        // 验证密码
        if (!employee.getPassword().equals(loginDTO.getPassword())) {
            log.warn("密码错误: {}", loginDTO.getUsername());
            return null;
        }
        
        // 生成JWT令牌
        String token = jwtUtil.generateToken(employee.getId(), employee.getUsername());
        log.info("登录成功: {}", loginDTO.getUsername());
        
        // 封装返回结果
        return new LoginResponseDTO(
                employee.getId(),
                employee.getUsername(),
                employee.getName(),
                token
        );
    }
} 